﻿@section header {
    <script type="text/javascript">

        var privilegeNewOrEdit, privilegeDelete;
        Ext.onReady(function () {
//            Ext.tree.View.extend({
//                getRecords: function (nodes) {
//                    var records = Ext.create("Ext.util.MixedCollection");

//                    for (var i = 0, ilen = nodes.length; i < ilen; i++)
//                        records.add(i, this.store.data.getByKey(nodes[i].viewRecordId));

//                    return records;
//                },

//                getChecked: function () {
//                    var records = this.getRecords(this.getNodes());
//                    return records.filterBy(function (record, i, k) {
//                        return record.data.checked;
//                    });
//                }
//            });  

            var treep = new Ext.tree.TreePanel({
                title: '模块功能树',
                //selModel: new Ext.selection.CheckboxModel({}),
                tbar: [
                { xtype: 'button', iconCls: 'iconNew', text: '', tooltip: '增加', tooltipType: 'title', handler: function (source, e) { treepNodeNewOrEdit(null) } },
                { xtype: 'button', iconCls: 'iconEdit', text: '', tooltip: '编辑', tooltipType: 'title', handler: function (source, e) { treepNodeNewOrEdit(treep.selModel.selected.items[0].get("id")); } },
                { xtype: 'button', iconCls: 'iconDelete', text: '', tooltip: '删除', tooltipType: 'title', handler: function (source, e) { treeqRemoveNode(treep.selModel.selected.items[0].get("id")) } },
                { xtype: 'tbseparator' },
                { xtype: 'button', iconCls: 'iconSave', text: '', tooltip: '保存调整排序', tooltipType: 'title', handler: function (source, e) { treeqReorderNodes(treep.getView()) } },
                { xtype: 'tbfill' },
                { xtype: 'button', iconCls: 'iconRefresh', text: '', tooltip: '刷新', tooltipType: 'title', handler: function (source, e) { treep.getView().getTreeStore().load() } }
             ],
                store: new Ext.data.TreeStore({
                    proxy: {
                        type: 'ajax',
                        url: '/data/Privilege/moduleResourceTree'
                    },
                    root: {
                        text: '所有模块功能',
                        expanded: true
                    }/*,
                folderSort: true,
                sorters: [{
                    property: 'text',
                    direction: 'ASC'
                }]*/
                }),
                singleSelect: true,
                frame: true,
                simpleSelect: false,
                margin: 6, bodyPadding: 0, padding: 0, autoScroll: true,
                viewConfig: {
                    plugins: {
                        ptype: 'treeviewdragdrop', //就是Ext.tree.ViewDDPlugin
                        listeners: {
                            beforedrop: function () { alert("sss") }
                        }
                    }
                },
                listeners: {
                    itemclick: function (view, record, item, index, e) {
                                            //debugger;
                        privilegeGridRefresh()
                    },
                    selectionchange: function (view, selections) { },
                    itemdbclick: function (view, record, item, index, e) {
                        //alert(record.get('id') + ' clicked!');
                        //debugger;
                        winMR.eData = record;
                        winMR.show(this);
                    },
                    itemcontextmenu: function (view, record, el, index, event) {// 声明菜单类型
                        event.preventDefault(); // 阻止浏览器默认右键菜单显示
                        var nodeType = record.data.depth = 0 ? "模块" : "资源";
                        //                    m.selRecord = record;  //treep被选中的是treep.selModel.selected.items[0].get("id")
                        Ext.create("Ext.menu.Menu", {
                            items: [
                            { id: 'rMenu1', text: '添加' + nodeType, iconCls: 'iconNew', handler: function () { treepNodeNewOrEdit(null); } },
                            { id: 'rMenu2', text: '编辑' + nodeType, iconCls: 'iconEdit', handler: function (n, e) { treepNodeNewOrEdit(record.data.id); } },
                            { id: 'rMenu3', text: '删除' + nodeType, iconCls: 'iconDelete', handler: function () { treeqRemoveNode(record.data.id) } }
                            ]
                        }).showAt(event.getXY());
                    },
                    scope: this
                }
            });

            treep.on('checkchange', function (node, checked) {
                debugger;
                node.expand();
                node.attributes.checked = checked;
                node.eachChild(function (child) {
                    child.ui.toggleCheck(checked);
                    child.attributes.checked = checked;
                    child.fireEvent('checkchange', child, checked);
                });
            }, treep);


            var treeqReorderNodes = function (view) {

                Ext.Ajax.request({
                    url: '/system/auth/ReOrderModules',
                    params: {
                        data: view.store.data.keys
                    },
                    success: function (response) {
                        alert("success");
                        treep.getView().getTreeStore().load();
                        //var text = response.responseText;
                        // process server response here
                    },
                    failure: function (response) {
                        alert("failure");
                    }
                });
            }

            var treeqRemoveNode = function (id) {
                //alert('删除'+nodeType+':' + this.parentMenu.selRecord.get('id')); 
                Ext.Ajax.request({
                    url: '/system/auth/DeleteModule',
                    params: {
                        ID: id
                    },
                    success: function (response) {
                        alert("success");
                        treep.getView().getTreeStore().load();
                        //var text = response.responseText;
                        // process server response here
                    },
                    failure: function (response) {
                        alert("failure");
                    }
                });
            };

            var treepNodeNewOrEdit = function (id) {
                var isModule = treep.selModel.selected.items[0].data.depth < 2;
                new Ext.window.Window({
                    id: 'fwin',
                    title: isModule ? '模块信息' : '功能信息',
                    modal: true,
                    closable: true,
                    stateful: false,
                    //animateTarget: this,
                    width: 600,
                    //height: 500,
                    layout: 'fit',
                    bodyStyle: 'padding: 5px;',
                    items: [
                    isModule ? new MB.form.Module({
                        id: id,
                        close: function () { Ext.getCmp('fwin').destroy(); },
                        submitSccess: function (form, action) { Ext.getCmp('fwin').destroy(); treep.getView().getTreeStore().load(); ; alert("submitSccess"); },
                        submitFailure: function (form, action) { alert("submitFailure"); }
                    }) :
                    new MB.form.Resource({
                        id: id,
                        close: function () { Ext.getCmp('fwin').destroy(); },
                        submitSccess: function (form, action) { Ext.getCmp('fwin').destroy(); treep.getView().getTreeStore().load(); ; alert("submitSccess"); },
                        submitFailure: function (form, action) { alert("submitFailure"); }
                    })
                ]
                }).show();
            }

            var privilegeGridRefresh = function () {

                grid.getView().getStore().load({
                    params: {
                        mrId/*当前的模块功能节点*/: treep.selModel.selected.items.length > 0 ? treep.selModel.selected.items[0].get("id") : "",
                        depth: treep.selModel.selected.items.length > 0 ? treep.selModel.selected.items[0].data.depth : 0
                    }
                })
            }

            Ext.regModel('Privileges', {
                //            fields: ['ID','privilegeName', 'resourceCode', 'privilegeCode']
                fields: [
            { name: 'ID', type: 'string' },
            { name: 'privilegeName', type: 'string' },
            { name: 'resourceName', type: 'string' },
            { name: 'moduleName', type: 'string' },
            { name: 'privilegeCode', type: 'string' },
            { name: 'needAuth', type: 'boolean' },
            { name: 'isMenuEntry', type: 'boolean' },
             { name: 'createdTime', type: 'date' },
            { name: 'orderNO', type: 'int' }
            ]
            });

            var grid = new Ext.grid.GridPanel({
                id: 'grid001',
                frame: true,
                store: new Ext.data.Store({
                    model: 'Privileges',
                    sorters: ['orderNO'],
                    groupField: 'moduleName',
                    proxy: {
                        type: 'ajax',
                        url: '/data/Privilege',
                        //                    params: {mrId/*当前的模块功能节点*/: treep.selModel.selected.items.length>0?treep.selModel.selected.items[0].get("id"):""},
                        extraParams: { mrId: '', depth: 0 }, //传参数,在Request.Params["mrId"]
                        //params: {mrId:'params'},
                        reader: {
                            type: 'json',
                            root: 'data'
                        }
                    },
                    autoLoad: true
                }),
                margin: 6,
                //width: 400,
                height: 300,
                flex: 3,
                //selModel: new Ext.selection.CheckboxModel({}),
                tbar: [
                { xtype: 'button', iconCls: 'iconNew', text: '', tooltip: '增加', tooltipType: 'title', handler: function (source, e) { privilegeNewOrEdit(null) } },
                { xtype: 'button', iconCls: 'iconEdit', text: '', tooltip: '编辑', tooltipType: 'title',
                    handler: function (source, e) {
                        privilegeNewOrEdit(grid.selModel.selected.items[0].data.ID
                )
                    }
                },
                { xtype: 'button', iconCls: 'iconDelete', text: '', tooltip: '删除', tooltipType: 'title',
                    handler: function (source, e) {
                        privilegeDelete(grid.selModel.selected.items[0].data.ID
                )
                    }
                },
                { xtype: 'tbseparator' },
                { xtype: 'tbfill' },
                { xtype: 'button', iconCls: 'iconRefresh', text: '', tooltip: '刷新', tooltipType: 'title', handler: function (source, e) { privilegeGridRefresh() } }
            ],
                title: '操作表',
                features: [{
                    ftype: 'grouping',
                    groupHeaderTpl: '模块: {name}' //API文档错误,groupHdTpl无效
                }],
                columns: [
                //new Ext.grid.RowNumberer(), //序号乱,暂时不显示
                {
                text: 'ID',
                flex: 1,
                dataIndex: 'ID',
                hidden: true
            }, {
                text: '操作编码',
                dataIndex: 'privilegeCode',
                width: 100
            }, {
                text: '操作名称',
                dataIndex: 'privilegeName',
                renderer: function (v) { return '<a href="#">' + v + '</a>'; },
                flex: 1
            }, {
                text: '功能',
                dataIndex: 'resourceName',
                width: 100
            }, {
                text: '需要授权',
                dataIndex: 'needAuth',
                renderer: function (v) { return v ? '是' : '否' },
                flex: 1
            }, {
                text: '是否入口',
                dataIndex: 'isMenuEntry',
                renderer: function (v) { return v ? '是' : '否' },
                flex: 1
            }, {
                text: '创建时间',
                dataIndex: 'createdTime',
                flex: 1
            }, {
                text: '操作',
                dataIndex: 'ID',
                renderer: function (v) { return '<span class="iconEdit" style="width:20px;height:18px;" title="修改" onclick=privilegeNewOrEdit("' + v + '")></span><span class="iconDelete" style="width:20px;height:18px;" title="删除" onclick=privilegeDelete("' + v + '")></span>'; },
                width: 50
            }],
            listeners: {
                itemdblclick: function (view, record, el, index, e) {
                }
            }
        });


        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            border: 0,
            items: [{
                //renderTo: Ext.getBody(),
                //region: 'center',
                layout: {
                    type: 'hbox',
                    align: 'stretch'
                    //pack: 'start'
                },
                //oadMask: { msg: 'Please wait...' },
                defaults: {
                    flex: 1 //子元素平均分配宽度
                },
                split: true,
                autoScroll: true,
                bodyPadding: 0,
                padding: 0,
                margin: 0,
                tbar: [
                { xtype: 'label', text: '权限管理 -> 模块功能操作项', cls: 'formNav' },
                { xtype: 'button', iconCls: 'iconRefresh', tooltip: '刷新，尚未实现！', tooltipType: 'title', handle: function (source, e) { window.location.href = window.location.href; } },
                { xtype: 'tbfill' },
                { xtype: 'button', iconCls: 'helpIcon', tooltip: '帮助', tooltipType: 'title', handle: function (source, e) { alert('帮助!') } },
                { xtype: 'button', iconCls: 'iconClose', text: '', tooltip: '关闭', tooltipType: 'title', handler: function (source, e) { window.parent.closeMe(window) } }
            ],
                bbar: [
                { xtype: 'button', text: 'Button 1', handler: function (source, e) { openWindow(); } }
            ],
                items: [treep, grid]
            }]
        });

        /*var*/privilegeNewOrEdit = function (id) { //privilegeNewOrEdit是全局变量
            new Ext.window.Window({
                id: 'fwinPrivilege',
                title: '模块信息' + id || '',
                modal: true,
                closable: true,
                //stateful: false,
                closeAction: 'destroy',
                //animateTarget: this,
                width: 600,
                //height: 500,
                layout: 'fit',
                bodyStyle: 'padding: 5px;',
                items: [
                    new MB.form.Privilege({
                        id: id,
                        close: function () { Ext.getCmp('fwinPrivilege').close(); },
                        submitSccess: function () { alert("submitSccess"); grid.getView().getStore().load(); Ext.getCmp('fwinPrivilege').close(); },
                        submitFailure: function () { alert("submitFailure"); }
                    })
                ]
            }).show();
        }

        privilegeDelete = function (id) {
            //alert('删除'+nodeType+':' + this.parentMenu.selRecord.get('id')); 
            Ext.Ajax.request({
                url: '/system/auth/DeletePrivilege',
                params: {
                    ID: id
                },
                success: function (response) {
                    alert("success");
                    grid.getView().getStore().load();
                },
                failure: function (response) {
                    alert("failure");
                }
            });
        };
    })
    </script>
}
